package cn.lblbc.webbrowser

import android.Manifest
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.view.LayoutInflater
import android.widget.Button
import android.widget.EditText
import android.widget.ImageButton
import android.widget.LinearLayout
import android.widget.Switch
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.lblbc.webbrowser.utils.ImageCollectionSettings
import cn.lblbc.webbrowser.utils.ImageCollector
import cn.lblbc.webbrowser.utils.BackgroundImageManager
import cn.lblbc.webbrowser.utils.PasswordManager
import cn.lblbc.webbrowser.adapters.BackgroundImageAdapter
import cn.lblbc.webbrowser.adapters.SimpleBackgroundImageAdapter
import cn.lblbc.webbrowser.adapters.BackgroundImageItem
import cn.lblbc.webbrowser.adapters.BackgroundImageType
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream

class SettingsActivity : BaseActivity() {
    
    private lateinit var closeButton: ImageButton
    private lateinit var imageCollectionSwitch: Switch
    private lateinit var resolutionSettingLayout: LinearLayout
    private lateinit var resolutionValueText: TextView
    private lateinit var backgroundImageSwitch: Switch
    private lateinit var backgroundImageLayout: LinearLayout
    private lateinit var backgroundImageValueText: TextView
    private lateinit var changePasswordLayout: LinearLayout  // 添加修改密码布局引用
    private lateinit var imageCollectionSettings: ImageCollectionSettings
    private lateinit var backgroundImageManager: BackgroundImageManager
    private lateinit var passwordManager: PasswordManager
    private lateinit var aiProgrammingLayout: LinearLayout
    
    // 图片选择器
    private val imagePickerLauncher = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) { result ->
        if (result.resultCode == RESULT_OK) {
            result.data?.data?.let { uri ->
                handleSelectedImage(uri)
            }
        }
    }
    
    // 权限请求
    private val permissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestPermission()
    ) { isGranted ->
        if (isGranted) {
            openImagePicker()
        } else {
            Toast.makeText(this, "需要存储权限才能选择图片", Toast.LENGTH_SHORT).show()
        }
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_settings)
        
        imageCollectionSettings = ImageCollectionSettings(this)
        backgroundImageManager = BackgroundImageManager(this)
        passwordManager = PasswordManager(this)
        
        initViews()
        setupListeners()
        updateUI()
    }
    
    private fun initViews() {
        closeButton = findViewById(R.id.closeButton)
        imageCollectionSwitch = findViewById(R.id.imageCollectionSwitch)
        resolutionSettingLayout = findViewById(R.id.resolutionSettingLayout)
        resolutionValueText = findViewById(R.id.resolutionValueText)
        backgroundImageSwitch = findViewById(R.id.backgroundImageSwitch)
        backgroundImageLayout = findViewById(R.id.backgroundImageLayout)
        backgroundImageValueText = findViewById(R.id.backgroundImageValueText)
        changePasswordLayout = findViewById(R.id.changePasswordLayout)  // 初始化修改密码布局引用
        aiProgrammingLayout = findViewById(R.id.aiProgrammingLayout)
    }
    
    private fun setupListeners() {
        closeButton.setOnClickListener {
            finish()
        }
        
        imageCollectionSwitch.setOnCheckedChangeListener { _, isChecked ->
            imageCollectionSettings.isEnabled = isChecked
            updateResolutionSettingVisibility()
        }
        
        resolutionSettingLayout.setOnClickListener {
            showResolutionDialog()
        }
        
        backgroundImageSwitch.setOnCheckedChangeListener { _, isChecked ->
            backgroundImageManager.setBackgroundImageEnabled(isChecked)
            updateBackgroundImageLayoutState()
            
            // 发送广播通知 HomeFragment 刷新背景
            val intent = Intent("BACKGROUND_IMAGE_CHANGED")
            LocalBroadcastManager.getInstance(this).sendBroadcast(intent)
        }
        
        backgroundImageLayout.setOnClickListener {
            if (backgroundImageSwitch.isChecked) {
                showBackgroundImageDialog()
            }
        }
        
        // 添加修改密码点击事件
        changePasswordLayout.setOnClickListener {            
            showChangePasswordDialog()
        }
        
        // 添加学习AI编程点击事件
        aiProgrammingLayout.setOnClickListener {
            val url = "https://cxyxy.blog.csdn.net/article/details/151590489"
            val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
            startActivity(intent)
        }
    }
    
    private fun updateUI() {
        imageCollectionSwitch.isChecked = imageCollectionSettings.isEnabled
        resolutionValueText.text = imageCollectionSettings.getResolutionDescription(this)
        updateResolutionSettingVisibility()
        updateBackgroundImageUI()
        updateBackgroundImageSwitchState()
        updateBackgroundImageLayoutState()
    }
    
    private fun updateBackgroundImageSwitchState() {
        backgroundImageSwitch.isChecked = backgroundImageManager.isBackgroundImageEnabled()
    }
    
    private fun updateBackgroundImageLayoutState() {
        val isEnabled = backgroundImageSwitch.isChecked
        backgroundImageLayout.isEnabled = isEnabled
        backgroundImageLayout.alpha = if (isEnabled) 1.0f else 0.5f
    }
    
    private fun updateResolutionSettingVisibility() {
        resolutionSettingLayout.alpha = if (imageCollectionSwitch.isChecked) 1.0f else 0.5f
        resolutionSettingLayout.isEnabled = imageCollectionSwitch.isChecked
    }
    
    private fun showResolutionDialog() {
        if (!imageCollectionSwitch.isChecked) return
        
        val options = arrayOf(
            getString(R.string.resolution_any),
            getString(R.string.resolution_small),
            getString(R.string.resolution_medium),
            getString(R.string.resolution_large),
            getString(R.string.resolution_xlarge),
            getString(R.string.resolution_custom)
        )
        
        val currentPreset = imageCollectionSettings.getCurrentPreset()
        
        AlertDialog.Builder(this, R.style.CustomAlertDialog)
            .setTitle(R.string.min_image_resolution)
            .setSingleChoiceItems(options, currentPreset) { dialog, which ->
                when (which) {
                    ImageCollectionSettings.RESOLUTION_CUSTOM -> {
                        dialog.dismiss()
                        showCustomResolutionDialog()
                    }
                    else -> {
                        imageCollectionSettings.setPresetResolution(which)
                        updateUI()
                        dialog.dismiss()
                    }
                }
            }
            .setNegativeButton(android.R.string.cancel, null)
            .show()
    }
    
    private fun showCustomResolutionDialog() {
        val dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_custom_resolution, null)
        val widthEdit = dialogView.findViewById<EditText>(R.id.widthEditText)
        val heightEdit = dialogView.findViewById<EditText>(R.id.heightEditText)
        
        // 设置当前值
        if (imageCollectionSettings.getCurrentPreset() == ImageCollectionSettings.RESOLUTION_CUSTOM) {
            widthEdit.setText(imageCollectionSettings.minWidth.toString())
            heightEdit.setText(imageCollectionSettings.minHeight.toString())
        }
        
        AlertDialog.Builder(this, R.style.CustomAlertDialog)
            .setTitle(R.string.custom_resolution_title)
            .setView(dialogView)
            .setPositiveButton(android.R.string.ok) { _, _ ->
                val widthStr = widthEdit.text.toString()
                val heightStr = heightEdit.text.toString()
                
                try {
                    val width = widthStr.toInt()
                    val height = heightStr.toInt()
                    
                    if (width >= 0 && height >= 0) {
                        imageCollectionSettings.minWidth = width
                        imageCollectionSettings.minHeight = height
                        updateUI()
                    } else {
                        Toast.makeText(this, R.string.invalid_resolution, Toast.LENGTH_SHORT).show()
                    }
                } catch (e: NumberFormatException) {
                    Toast.makeText(this, R.string.invalid_resolution, Toast.LENGTH_SHORT).show()
                }
            }
            .setNegativeButton(android.R.string.cancel, null)
            .show()
    }
    
    private fun updateBackgroundImageUI() {
        backgroundImageValueText.text = backgroundImageManager.getBackgroundImageDisplayName()
    }
    
    private fun showBackgroundImageDialog() {
        val options = arrayOf(
            "内置图片",
            "从相册选择",
            "从文件管理器选择"
        )
        
        AlertDialog.Builder(this, R.style.CustomAlertDialog)
            .setTitle("选择背景图片")
            .setItems(options) { _, which ->
                when (which) {
                    0 -> showBuiltInImagesDialog()
                    1 -> requestStoragePermissionAndOpenPicker()
                    2 -> requestStoragePermissionAndOpenFilePicker()
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }
    
    /**
     * 请求存储权限并打开文件选择器
     */
    private fun requestStoragePermissionAndOpenFilePicker() {
        when {
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU -> {
                // Android 13+ 不需要存储权限来访问媒体文件
                openFilePicker()
            }
            ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.READ_EXTERNAL_STORAGE
            ) == PackageManager.PERMISSION_GRANTED -> {
                openFilePicker()
            }
            else -> {
                permissionLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE)
            }
        }
    }
    
    /**
     * 打开文件选择器
     */
    private fun openFilePicker() {
        val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
            addCategory(Intent.CATEGORY_OPENABLE)
            type = "image/*"
            putExtra(Intent.EXTRA_ALLOW_MULTIPLE, false)
        }
        imagePickerLauncher.launch(intent)
    }
    
    /**
     * 显示内置图片选择对话框
     */
    private fun showBuiltInImagesDialog() {
        val dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_background_image_selector, null)
        val recyclerView = dialogView.findViewById<RecyclerView>(R.id.backgroundImageRecyclerView)
        val selectFromGalleryButton = dialogView.findViewById<Button>(R.id.selectFromGalleryButton)
        val cancelButton = dialogView.findViewById<Button>(R.id.cancelButton)
        
        // 隐藏"从相册选择"按钮，因为这里只显示内置图片
        selectFromGalleryButton.visibility = android.view.View.GONE
        
        // 准备内置图片数据
        val items = prepareBuiltInImageItems()
        val currentBackground = backgroundImageManager.getCurrentBackgroundImage()
        
        android.util.Log.d("SettingsActivity", "Current background: $currentBackground")
        android.util.Log.d("SettingsActivity", "Items count: ${items.size}")
        items.forEachIndexed { index, item ->
            android.util.Log.d("SettingsActivity", "Item $index: ${item.imagePath}")
        }
        
        val dialog = AlertDialog.Builder(this, R.style.CustomAlertDialog)
            .setView(dialogView)
            .create()
        
        // 设置RecyclerView为网格布局
        recyclerView.layoutManager = GridLayoutManager(this, 2) // 2列网格
        val adapter = SimpleBackgroundImageAdapter(this, items, currentBackground) { selectedItem ->
            // 保存选择的背景图片
            backgroundImageManager.setBackgroundImage(selectedItem.imagePath)
            updateBackgroundImageUI()
            
            // 添加调试信息
            android.util.Log.d("BackgroundImage", "Selected: ${selectedItem.imagePath}")
            android.util.Log.d("BackgroundImage", "Current saved: ${backgroundImageManager.getCurrentBackgroundImage()}")
            
            // 发送广播通知 HomeFragment 刷新背景
            val intent = Intent("BACKGROUND_IMAGE_CHANGED")
            LocalBroadcastManager.getInstance(this).sendBroadcast(intent)
            
            // 显示成功提示
            Toast.makeText(this, "背景图片已设置", Toast.LENGTH_SHORT).show()
            
            dialog.dismiss()
        }
        recyclerView.adapter = adapter
        
        cancelButton.setOnClickListener {
            dialog.dismiss()
        }
        
        dialog.show()
    }
    
    /**
     * 准备内置图片选择项数据
     */
    private fun prepareBuiltInImageItems(): List<BackgroundImageItem> {
        val items = mutableListOf<BackgroundImageItem>()
        
        // 添加不使用背景图片的选项
        items.add(BackgroundImageItem(
            id = "none",
            title = "不使用背景",
            subtitle = "显示纯色背景",
            imagePath = null,
            type = BackgroundImageType.DEFAULT
        ))
        
        // 添加默认背景 - 使用特殊标识符"default"而不是null
        items.add(BackgroundImageItem(
            id = "default",
            title = "默认背景",
            subtitle = "使用应用默认背景",
            imagePath = "default",
            type = BackgroundImageType.DEFAULT
        ))
        
        // 添加内置图片
        val bundledImages = backgroundImageManager.getBundledImages()
        bundledImages.forEach { imageName ->
            items.add(BackgroundImageItem(
                id = imageName,
                title = imageName.removePrefix("img_").replace("_", " "),
                subtitle = "内置图片",
                imagePath = imageName,
                type = BackgroundImageType.BUNDLED
            ))
        }
        
        return items
    }
    
    /**
     * 获取自定义背景图片列表
     */
    private fun getCustomBackgrounds(): List<File> {
        return try {
            val backgroundDir = File(getExternalFilesDir(null), "Pictures/Backgrounds")
            if (backgroundDir.exists()) {
                backgroundDir.listFiles { file ->
                    file.isFile && file.extension.lowercase() in listOf("jpg", "jpeg", "png", "gif", "webp")
                }?.sortedByDescending { it.lastModified() }?.toList() ?: emptyList()
            } else {
                emptyList()
            }
        } catch (e: Exception) {
            e.printStackTrace()
            emptyList()
        }
    }
    
    /**
     * 请求存储权限并打开图片选择器
     */
    private fun requestStoragePermissionAndOpenPicker() {
        when {
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU -> {
                // Android 13+ 不需要存储权限来访问媒体文件
                openImagePicker()
            }
            ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.READ_EXTERNAL_STORAGE
            ) == PackageManager.PERMISSION_GRANTED -> {
                openImagePicker()
            }
            else -> {
                permissionLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE)
            }
        }
    }
    
    /**
     * 打开图片选择器
     */
    private fun openImagePicker() {
        val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI).apply {
            type = "image/*"
        }
        imagePickerLauncher.launch(intent)
    }
    
    /**
     * 处理选择的图片
     */
    private fun handleSelectedImage(uri: Uri) {
        try {
            // 将选择的图片复制到应用的私有目录
            val inputStream: InputStream? = contentResolver.openInputStream(uri)
            if (inputStream != null) {
                val fileName = "custom_background_${System.currentTimeMillis()}.jpg"
                val backgroundDir = File(getExternalFilesDir(null), "Pictures/Backgrounds").apply {
                    if (!exists()) {
                        mkdirs()
                    }
                }
                val outputFile = File(backgroundDir, fileName)
                
                FileOutputStream(outputFile).use { outputStream ->
                    inputStream.copyTo(outputStream)
                }
                
                // 设置为背景图片
                backgroundImageManager.setBackgroundImage(outputFile.absolutePath)
                updateBackgroundImageUI()
                
                // 发送广播通知 HomeFragment 刷新背景
                val intent = Intent("BACKGROUND_IMAGE_CHANGED")
                LocalBroadcastManager.getInstance(this).sendBroadcast(intent)
                
                Toast.makeText(this, "背景图片已设置", Toast.LENGTH_SHORT).show()
            }
        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(this, "设置背景图片失败", Toast.LENGTH_SHORT).show()
        }
    }


    // 显示修改密码对话框
    private fun showChangePasswordDialog() {
        val dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_change_password, null)
        val newPasswordEditText = dialogView.findViewById<EditText>(R.id.newPasswordEditText)
        val cancelButton = dialogView.findViewById<Button>(R.id.cancelButton)
        val confirmButton = dialogView.findViewById<Button>(R.id.confirmButton)

        val dialog = AlertDialog.Builder(this, R.style.CustomAlertDialog)
            .setView(dialogView)
            .setCancelable(true)
            .create()

        cancelButton.setOnClickListener {
            dialog.dismiss()
        }

        confirmButton.setOnClickListener {
            val newPassword = newPasswordEditText.text.toString()

            if (validatePasswordChange(newPassword)) {
                // 保存新密码
                passwordManager.setPassword(newPassword)
                dialog.dismiss()
                Toast.makeText(this, "密码修改成功", Toast.LENGTH_SHORT).show()
            }
        }

        dialog.show()
    }

    /**
     * 验证密码修改输入
     */
    private fun validatePasswordChange(newPassword: String): Boolean {
        // 检查新密码是否为空
        if (newPassword.isEmpty()) {
            Toast.makeText(this, "新密码不能为空", Toast.LENGTH_SHORT).show()
            return false
        }

        return true
    }
}

